﻿(function () {
    'use strict';

    // Custom event raised after the fragment is appended to the DOM.
    WinJS.Application.addEventListener('fragmentappended', function handler(e) {
        if (e.location === '/html/categoryPage.html') {
            fragmentLoad(e.fragment, e.state);
        }
    });

    function updateForLayout(lv, layout) {
        var layoutState = Windows.UI.ViewManagement.ApplicationLayoutState;
        if (layout === layoutState.snapped) {
            lv.layout = new WinJS.UI.ListLayout();
        } else {
            lv.layout = new WinJS.UI.GridLayout();
        }
        lv.refresh();
    }

    function layoutChanged(e) {
        var list = document.querySelector('.categoryList');
        if (list) {
            var lv = WinJS.UI.getControl(list);
            updateForLayout(lv, e.layout);
        }
    }

    function fragmentLoad(elements, options) {
        try {
            var appLayout = Windows.UI.ViewManagement.ApplicationLayout.getForCurrentView();
            if (appLayout) {
                appLayout.addEventListener('layoutchanged', layoutChanged);
            }
        } catch (e) { }

        WinJS.UI.processAll(elements)
            .then(function () {
            var lv = WinJS.UI.getControl(elements.querySelector('.categoryList'));
            WinJS.xhr({ "url": "data/index.js" }).then(function (response) {
                exampleList = JSON.parse(response.responseText);
                WinJS.UI.setOptions(lv, {
                    dataSource: exampleList,
                    itemRenderer: elements.querySelector('.itemTemplate'),
                    oniteminvoked: itemInvoked,
                });
                updateForLayout(lv, Windows.UI.ViewManagement.ApplicationLayout.value);
            }, function (response) {
                console.log("Error with XHR");
            });

        });

        return;
    }

    var exampleList = [];

    function itemInvoked(e) {
        WinJS.Navigation.navigate('/html/splitPage.html', exampleList[e.detail.itemIndex]);
    }

    WinJS.Namespace.define('categoryPage', {
        fragmentLoad: fragmentLoad,
        itemInvoked: itemInvoked
    });
})();
